-- Don't load this multiple times!
if LUA_SKYB then
    return
end

rawset(_G, "LUA_SKYB", 1)

--
-- "global" variables related to script
--
local skyboxmo = {} -- table containing skybox mobjs
local checkedskyboxes = false -- variable to make sure joining a server mid-game doesn't CONSTANTLY recheck skyboxes

--
-- ResetSkyboxStats
--
-- Reset skybox lists and other vars
--
local function ResetSkyboxStats()
	--print("resetting stats...")
	skyboxmo = {}
	checkedskyboxes = false
end

addHook("MapLoad", ResetSkyboxStats) -- hook the function

--
-- FindSkyboxes
--
-- Collects all the skybox viewpoint mobjs in the map, and counts up the number in said map
--
local function FindSkyboxes()
	-- collect the new viewpoints through map things, so we don't have to suffer lag
	for mapthing in mapthings.iterate do
		if mapthing.type != mobjinfo[MT_SKYBOX].doomednum then
			continue -- not the right Map thing number
		end
		if mapthing.options & MTF_OBJECTSPECIAL then
			continue -- not a viewpoint
		end
		if not mapthing.mobj then
			continue -- ???? (skybox thing types should all have mobjs)
		end

		table.insert(skyboxmo, mapthing.mobj)
		--print("skybox found!")
	end

	checkedskyboxes = true -- yes, you've checked for them now, don't bother us anymore
end

-- minor function to make sure FindSkyboxes() is called ONLY when it hasn't been checked before
local function Stuff()
	if not checkedskyboxes then
		FindSkyboxes()
		--print(numskyboxes+" skyboxes found!")
	end
end

addHook("ThinkFrame", Stuff) -- hook the function

--
-- SetSkyboxLE
--
-- Used by any Linedef type 443s with the name "SETSKYBX" in front upper texture:
-- Sets the skybox number determined by texture offsets for the triggering player.
-- As a bonus, ML_NOCLIMB affects all players, if you like!
--
local function SetSkyboxLE(line, mobj)
	local id = line.frontside.textureoffset>>FRACBITS -- front side's x-offsets, scaled down to regular integers

	if #skyboxmo == 0 then
		print("ERROR: (SETSKYBX for line #"+#line+") No skyboxes in map!") -- note: #line prints linedef number
	end

	if (id <= 0) or (id > #skyboxmo) then
		print("ERROR: (SETSKYBX for line #"+#line+") Skybox id is out of range!")
	end

	if line.flags & ML_NOCLIMB then
		-- doesn't really matter what type of object triggered it here
		P_SetSkyboxMobj(skyboxmo[id]) -- apply skybox to all players!
	else
		if not mobj.player then
			return -- only supposed to be triggered by a player!
		end
		P_SetSkyboxMobj(skyboxmo[id], mobj.player) -- apply skybox to only the triggering player
	end
end

addHook("LinedefExecute", SetSkyboxLE, "SETSKYBX") -- hook the function
